<?php
namespace Home\Controller;
use Home\Model\UserModel;
class SignController extends BaseController {
	public $_APPID ='';
	public $_AppSecret ='';
	 public function __construct(){
    	parent::__construct();
	 	$this->_APPID = C('APPID');
	 	$this->_AppSecret = C('AppSecret');
	 }
	public function add(){
		$userModel = new UserModel();  
		//用户授权登陆获取基本信息
		$code = I('get.code');
		$state = I('get.state');
		$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->_APPID.'&secret='.$this->_AppSecret.'&code='.$code.'&grant_type=authorization_code';
		$res = $this->request_get($get_token_url);
		$json_obj = json_decode($res,true);
		//根据openid和access_token查询用户信息
		$access_token = $json_obj['access_token'];
		$openid = $json_obj['openid'];
		$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		$res = $this->request_get($get_user_info_url);
		//解析json
		$wxData = json_decode($res,true);
		
		if($state =='courseList'||$state=='mycourse'){
			$userData = $wxData;
	    	$isExistUserData['openid'] = $userData['openid'];
			$isExistUserResult = $userModel->getUserItem($isExistUserData);
			if($isExistUserResult){
				$sign_cookie['sessionid']=$isExistUserResult['sessionid'];
				$this->loginsetcookie($sign_cookie, 60*60*24*7, '/');
			}else {
				//用户新增
				$userData['sessionid']=md5(uniqid(rand(), TRUE));
		    	$userResult = $userModel->addUser($userData);
				$sign_cookie['sessionid']=$userData['sessionid'];
				$this->loginsetcookie($sign_cookie, 60*60*24*7, '/');
			}
			//根据不同操作，跳转不同方法
			if($state =='courseList'){
			    $this->redirect('Index/courseList');
			}elseif($state=='mycourse'){
			    $this->redirect('Index/mycourse');
			}
		}
	}
	/**
	 * cookie设置
	 * @param $var 设置的cookie名
	 * @param $value 设置的cookie值
	 * @param $life 设置的过期时间：为整型，单位秒 如60表示60秒后过期
	 * @param $path 设置的cookie作用路径
	 * @param $domain 设置的cookie作用域名
	 */
	public function loginsetcookie($array, $life=0, $path = '/') {
		$_cookName_ary = array_keys($array);
		for($i = 0; $i < count($array); $i++) {
			//echo $_cookName_ary[$i].'='.$array[$_cookName_ary[$i]].'<br>';
			$httpOnly = false;
			setcookie($_cookName_ary[$i], $array[$_cookName_ary[$i]], $life?(time()+$life):0, $path);
		}
	}
    
}